<?php

namespace BasicAdmin\Modules\User\Apis;

use BasicAdmin\Models\UserModel;
use Exception;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use mszl\api\utils\ApiUtils;

class Login
{
    public static function route(): void
    {
        //登录
        Route::get('/test', [self::class, 'test']);
        Route::post('/login', [self::class, 'login']);
        Route::post('/upload', [self::class, 'upload']);

    }
    public static function upload(Request $request): array
    {
        $path = "images";
        if ($file = $request->file('file')) {
            $size = $file->getSize(); //412887
            //大小控制，图片裁剪
            if ($size > 2000 * 1024) {
                throw new Exception('Exceeded file size limit');
            }

            $path = $file->store($path);
            return [
                'pic_id' => str_replace("public/", "", $path),
                'avatar' => ApiUtils::pic(str_replace("public/", "", $path)),
            ];
        }
        throw new Exception('file not found');
    }
    public static function test(): string
    {
        return 'test api';
    }

    /**
     * @throws Exception
     */
    public static function login(): array
    {
        extract(ApiUtils::getParams());
        $info = UserModel::get(['password','id'], ['account' => $account, 'state' => 0]);
        if (empty($info)) throw new Exception('用户名或者密码错误');
        if (!ApiUtils::passwordValidate($passwd, $info['password'])) throw new Exception('用户名或者密码错误');
        //生成token，并返回
        $uid = $info['id'];
        $token = ApiUtils::password($uid . ":" . time());
        ApiUtils::getRedis()->setex(env('AUTHORIZATION_TOKEN') . ":" . $token, 86400 * 30, $uid);
        return ['token' => $token];
    }


}
